<template>
  <div class="app-container">
    <!-- <mainTilte title="系统sku映射管理" /> -->
    <div v-if="tabs === '1'">
      <form-selections :is-active="false" :items="formItems" :query-param.sync="searchParams" display="block" @handleSearch="handleSearch1" />
    </div>
    <div v-if="tabs === '2'">
      <form-selections :is-active="false" :items="formItemscb" :query-param.sync="queryParam" display="block" @handleSearch="handleSearch" />
    </div>
    <el-tabs v-model="tabs" type="card" style="margin-top:5px" @tab-click="handleClick">
      <el-tab-pane label="普通商品映射" name="1" :disabled="loading" />
      <el-tab-pane label="组合商品映射" name="2" :disabled="loading" />
    </el-tabs>
    <div v-if="tabs === '1'" class="page-grid">
      <div class="select_flex">
        <div class="operation_button_box">
          <el-button v-action="'productPlatformSku@save'" size="small" type="success" icon="el-icon-circle-plus-outline" @click="addClick">新增映射
          </el-button>
          <el-button v-action="'productPlatformSku@importSku'" size="small" type="primary" @click="handleImport">导入</el-button>
          <el-button v-action="'productPlatformSku@export'" size="small" type="primary" :loading="exportLoading" @click="handleExport">
            导出</el-button>
        </div>
        <div>
          <el-button size="small" type="primary" icon="el-icon-search" @click="handleSearch1">
            搜索
          </el-button>
          <el-button size="small" icon="el-icon-refresh" @click="handleRefresh1">
            刷新
          </el-button>
        </div>
      </div>
      <div v-loading="loading">
        <egrid :screen-heigh="screenHeigh" class="egrid" stripe fit border highlight-current-row element-loading-text="正在努力加载中..." :column-type="['selection']" :data="tableData" :columns="columns" :columns-schema="columnsSchema" :columns-handler="columnsHandler" @selection-change="checkIds" />
        <epagination v-if="tableData" :total="total" :current="searchParams.page" :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" @handleSizeChange="handleSizeChange1" @handleCurrentChange="handleCurrentChange1" />
      </div>
    </div>
    <div v-if="tabs === '2'">
      <div v-loading="loading" class="page-grid">
        <div class="select_flex">
          <div class="operation_button_box">
            <el-button v-action="'CombinationPlatformSku@save'" size="small" type="success" icon="el-icon-circle-plus-outline" @click="addClick">新增映射
            </el-button>
            <el-button v-action="'CombinationPlatformSku@importSku'" size="small" type="primary" @click="handleImport">导入</el-button>
            <el-button v-action="'CombinationPlatformSku@export'" size="small" type="primary" :loading="exportLoading" @click="handleExport">导出</el-button>
          </div>
          <div>
            <el-button size="small" type="primary" icon="el-icon-search" @click="handleSearch">搜索
            </el-button>
            <el-button size="small" icon="el-icon-refresh" @click="handleRefresh">
              刷新
            </el-button>
          </div>
        </div>
        <el-table :data="data" tooltip-effect="dark" style="width: 100%" border fit :max-height="screenHeigh">
          <el-table-column align="center" type="selection" width="55" />
          <el-table-column align="center" label="操作" width="200" fixed>
            <template slot-scope="scope">
              <span v-action="'CombinationPlatformSku@update'" class="edit_style" @click="editTable(scope.row)">编辑</span>
              <span v-action="'CombinationPlatformSku@delete'" class="delete_style" @click="handleDelete(scope.row.id)">删除</span>
            </template>
          </el-table-column>
          <el-table-column label="所属公司" align="center" prop="company_name" width="240" />
          <el-table-column label="所属店铺" align="center" prop="shop_name" width="150" />
          <el-table-column label="ERP编码" align="center" prop="product_code" width="180" />
          <el-table-column label="店铺对应编码" align="center" prop="platform_code" width="200px" />
          <el-table-column label="创建人" align="center" prop="creator_name" width="158px" />
          <el-table-column label="创建时间" align="center" prop="created_at" width="158px" />
          <el-table-column label="修改人" align="center" prop="update_name" width="158px" />
          <el-table-column label="修改时间" align="center" prop="updated_at" width="158px" />
        </el-table>
        <el-pagination v-if="paginate.total > 0" class="pagination_box" background :current-page="paginate.current" :page-sizes="[10, 20, 30, 40]" layout="total, sizes, prev, pager, next, jumper" :total="paginate.total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </div>
    <!-- 新增 -->
    <el-dialog v-if="addVisible" title="" :visible.sync="addVisible" :close-on-click-modal="true" width="30%" class="dialogText header-none" element-loading-text="正在加载中" element-loading-spinner="el-icon-loading" element-loading-background="rgba(0, 0, 0, 0.8)" :destroy-on-close="true">
      <el-form v-if="addVisible" ref="addForm" :model="addForm" :rules="addFormRules" label-width="120px">
        <el-row>
          <mainTilte title="ERP平台" />
        </el-row>
        <el-row>
          <el-col v-if="tabs==='1'" :span="24">
            <el-form-item label="ERP系统sku" prop="product_code">
              <app-select v-model="addForm.product_code" :url="urlSku" :params="productCodeParams" options-label="code" options-value="id" placeholder="请选择ERP系统sku" @change="handleSelect" />
            </el-form-item>
          </el-col>
          <el-col v-if="tabs==='2'" :span="24">
            <el-form-item label="所属店铺" prop="shop_id">
              <el-select v-model.trim="addForm.shop_id" filterable clearable placeholder="所属店铺" @change="changeShop">
                <el-option v-for="(item, index) of shopList" :key="index" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <mainTilte title="平台编码" />
        </el-row>
        <el-row>
          <el-col v-if="tabs==='2'" :span="24">
            <el-form-item label="ERP系统sku" prop="product_code">
              <app-select v-model="addForm.product_code" url="/combinationPlatformSkus/systemGoodsList" :params="productCodeParams2" options-label="code" options-value="id" placeholder="请选择ERP系统sku" @change="handleSelect" />
            </el-form-item>
          </el-col>
          <el-col v-if="tabs === '1'" :span="24">
            <el-form-item label="所属客户" prop="company_id">
              <el-select v-model.trim="addForm.company_id" clearable placeholder="所属客户" :disabled="true">
                <el-option v-for="(item, index) of companyList" :key="index" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col v-if="tabs === '1'" :span="24">
            <el-form-item label="所属店铺" prop="shop_id">
              <el-select v-model.trim="addForm.shop_id" filterable clearable placeholder="所属店铺" :disabled="tabs === '1'?false:true">
                <el-option v-for="(item, index) of shopList" :key="index" :label="item.name" :value="item.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="对应编码" prop="platform_code">
              <el-input v-model.trim="addForm.platform_code" placeholder="对应编码" oninput="value=value.replace(/[\u4E00-\u9FA5]/g,'')" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="btnLoading" @click="onSubmit">保存
        </el-button>
        <el-button @click="addVisible = false">取消</el-button>
      </span>
    </el-dialog>
    <!-- 导出 -->
    <down-modul :form-visible-down.sync="formVisibleDown" :url="downUrl" :search-param="searchParamObj" :options-modul="downOptions" />
    <!-- 导入 -->
    <import-dialog :url="importSku" title="导入系统sku映射" :form-visible.sync="importDialogVisible" @download="downLoad" @handleRefresh="handleRefresh" />
  </div>
</template>

<script>
import list from '@/layout/mixin/list'
import operationBtnGroup from '@/components/base/operationBtnGroup'
import DownModul from '@/components/DownModul/index'
import {
  action
} from '@/directive/permission/index.js' // 权限判断指令
import appText from '@/components/appText/index'
import {
  downloadStream
} from '@/utils/index'
import importDialog from '@/components/importDialog/index'
import formOperate from '@/layout/mixin/formOperate'
import cacheList from '@/layout/mixin/cacheList'
export default {
  name: 'CodeMapManage',
  components: {
    DownModul,
    importDialog
  },
  directives: {
    action
  },
  mixins: [list, formOperate, cacheList],
  data() {
    return {
      otherHeight: 415,
      importSku: '/productPlatformSkus/importSku',
      url: '/combinationPlatformSku',
      queryParam: {
        code: '',
        company_name: '',
        shop_name: ''
      },
      formItemscb: [{
        label: 'SKU',
        key: 'code',
        type: 'input',
        placeholder: '请输入系统sku/店铺Sku'
      },
      // {
      //   label: '店铺编码',
      //   key: 'platform_code',
      //   type: 'input',
      //   placeholder: '请输入店铺编码'
      // },
      {
        label: '所属店铺',
        key: 'shop_name',
        type: 'select',
        placeholder: '请选择店铺',
        filterable: true,
        options: []
      },
      {
        label: '客户名称',
        key: 'company_name',
        type: 'input',
        placeholder: '请输入客户名称'
      }
      ],
      // /combinationPlatformSkus/systemGoodsList
      urlSku: '/productPlatformSkus/systemGoodsList',
      tabs: '1',
      componentName: 'CodeMapManage',
      importDialogVisible: false,
      exportLoading: false,
      loading: false,
      loadingText: '',
      formItems: [{
        label: 'SKU',
        key: 'code',
        type: 'input',
        placeholder: '请输入系统sku/店铺Sku'
      },
      // {
      //   label: '店铺名称',
      //   key: 'shop_name',
      //   type: 'input',
      //   placeholder: '请输入店铺名称'
      // },
      {
        label: '所属店铺',
        key: 'shop_name',
        type: 'select',
        placeholder: '请选择店铺',
        filterable: true,
        options: []
      },
      {
        label: '客户名称',
        key: 'company_name',
        type: 'input',
        placeholder: '请输入客户名称'
      }
      ],
      /** *
         * 定义搜索框
         */
      searchParams: {
        page: 1,
        limit: 10, // 默认是10
        totalRows: 0,
        code: '',
        shop_name: '',
        company_name: ''
      },
      tableData: [{
        code: '111'
      }],
      /** *
         * 定义显示的表格
         */
      columns: [{
        label: '所属公司',
        prop: 'company_name',
        align: 'center',
        width: '240',
        tooltip: false
      },
      {
        label: '所属店铺',
        prop: 'shop_name',
        align: 'center',
        tooltip: false
      },
      {
        label: '店铺对应编码',
        prop: 'platform_code',
        width: '150',
        align: 'center',
        tooltip: false
      },
      {
        label: 'ERP编码',
        prop: 'product_code',
        width: '200',
        align: 'center',
        tooltip: false
      },
      {
        label: '创建人',
        prop: 'creator_name',
        width: '100',
        align: 'center',
        tooltip: false
      },
      {
        label: '创建时间',
        prop: 'created_at',
        width: '200',
        align: 'center',
        tooltip: false
      },
      {
        label: '修改人',
        prop: 'update_name',
        align: 'center',
        width: '150',
        component: appText,
        propsHandler({
          row
        }) {
          return {
            text: row.update_name
          }
        }
      },
      {
        label: '修改时间',
        prop: 'updated_at',
        width: '200',
        align: 'center',
        tooltip: false
      }
      ],
      /** *
         * 字典表组件
         */
      columnsSchema: {},
      addForm: {
        product_id: '',
        platform_code: '',
        company_id: '',
        company_name: '',
        shop_id: '',
        shop_name: '',
        product_code: ''
      },
      addVisible: false,
      addFormRules: {
        platform_code: [{
          required: true,
          message: '请输入系统sku',
          trigger: ['change', 'blur']
        }],
        company_id: [{
          required: true,
          message: '请选择所属公司',
          trigger: ['change', 'blur']
        }],
        shop_id: [{
          required: true,
          message: '请选择所属店铺',
          trigger: ['change', 'blur']
        }],
        product_code: [{
          required: true,
          message: '请输入对应编码',
          trigger: ['change', 'blur']
        }]
      },
      btnLoading: false,
      freightList: [],
      companyList: [],
      shopList: [],
      isEdit: false,
      formVisibleDown: false,
      downVisible: false, // 导出 visible
      downUrl: '/productPlatformSkus/export', // 导出 url
      downOptions: [{
        key: 'product_code',
        label: 'ERP编码'
      },
      {
        key: 'platform_code',
        label: '店铺对应编码'
      },
      {
        key: 'company_name',
        label: '所属公司'
      },
      {
        key: 'shop_name',
        label: '所属店铺'
      }
        // { key: 'product_code', label: 'ERP编码' },
        // { key: 'created_at', label: '创建时间' }
      ], // 导出 options
      productCodeParams: {
        // page: 1,
        // limit: 100000000,
        // status: 1,
        // is_disable: 1,
        // type: 0,
        is_multi_split: 0
      },
      productCodeParams2: {
        shop_id: ''
      }
    }
  },
  computed: {
    searchParamObj() {
      const vm = this
      return {
        code: vm.searchParams.code
      }
    }
  },
  created() {
    // 调用全局混合方法 第一个参数是请求地址对应的名称（api.js），第二个为参数
    this.query()
    this.getShop()
  },
  mounted() {
    if (this.tabs === '1') {
      this.querycompanyAsync()
    }
  },
  methods: {
    // 修改新增店铺 组合映射
    changeShop(value) {
      this.productCodeParams2.shop_id = value
      this.addForm.product_code = ''
    },
    // 获取店铺
    getShop() {
      const vm = this
      const params = { limit: 100000, page: 1 }
      vm.$http.get(`/shop`, { params: params }).then(res => {
        const data = res.data.map((arr) => {
          return {
            value: arr.shop_name,
            label: arr.shop_name
          }
        })
        vm.formItemscb = vm.formItemscb.map(arr => {
          if (arr.key === 'shop_name') {
            arr.options = data
          }
          return arr
        })
        vm.formItems = vm.formItems.map(arr => {
          if (arr.key === 'shop_name') {
            arr.options = data
          }
          return arr
        })
      })
    },
    editTable(row) {
      const that = this
      that.isEdit = true
      that.addForm = JSON.parse(JSON.stringify(row))
      if (this.tabs === '2') {
        this.queryShopAsync()
      }
      that.addVisible = true
    },
    handleClick() {
      console.log('=======')
      if (this.tabs === '1') {
        this.downUrl = '/productPlatformSkus/export'
        this.importSku = '/productPlatformSkus/importSku'
        this.urlSku = '/productPlatformSkus/systemGoodsList'
        this.query()
      } else {
        this.handleSearch()
        this.downUrl = '/combinationPlatformSkus/export'
        this.importSku = '/combinationPlatformSkus/importSku'
        this.urlSku = '/combinationPlatformSkus/systemGoodsList'
        console.log('========', this.date)
      }
    },
    // 导入
    handleImport() {
      const vm = this
      vm.importDialogVisible = true
      console.log('=============')
    },
    // 下载导入模板
    downLoad() {
      const vm = this
      vm.$http
        .get('/productPlatformSkus/import/template', {
          responseType: 'blob'
        })
        .then((res) => {
          downloadStream(res, 'sku映射导入模板.xlsx')
        })
    },
    // 导出
    handleExport() {
      const vm = this
      vm.formVisibleDown = true
      //   vm.exportLoading = true
      //   const url = '/productPlatformSkus/export'
      //   const { code } = vm.searchParams
      //   const params = {
      //     code
      //   }
      //   vm.$http.post(url, params).then(res => {
      //     downloadxlsx(res.data)
      //     vm.exportLoading = false
      //   }).catch(() => {
      //     vm.exportLoading = false
      //   })
    },

    handleSearch1() {
      const vm = this
      vm.searchParams.page = 1
      vm.query()
    },
    handleRefresh1() {
      const vm = this
      vm.searchParams.page = 1
      vm.searchParams.limit = 10
      vm.searchParams.code = ''
      vm.searchParams.shop_name = ''
      vm.searchParams.company_name = ''
      vm.query()
    },
    initForm() {
      this.addForm = {
        product_id: '',
        platform_code: '',
        company_id: '',
        company_name: '',
        shop_id: '',
        shop_name: '',
        product_code: ''
      }
    },
    // 所属客户查询
    querycompanyAsync() {
      const params = {
        page: 1,
        limit: 1000
      }
      this.$http
        .get(`/company`, {
          params
        })
        .then((res) => {
          if (res.code === 10000 && res.data && res.data.length > 0) {
            this.companyList = res.data.map((item) => {
              return {
                name: item.name,
                id: item.id
              }
            })
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // 店铺查询
    queryShopAsync(company_id) {
      const params = {
        page: 1,
        limit: 100000000,
        status: 1,
        company_id: company_id ?? ''
      }
      this.$http
        .get(`/shop`, {
          params
        })
        .then((res) => {
          if (res.code === 10000 && res.data && res.data.length > 0) {
            this.shopList = res.data.map((item) => {
              return {
                name: item.shop_name,
                id: item.id
              }
            })
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    query() {
      this.initTableData(
        `/productPlatformSku?page=${this.searchParams.page}&limit=${this.searchParams.limit}&code=${this.searchParams.code}&shop_name=${this.searchParams.shop_name}&company_name=${this.searchParams.company_name}`
      )
    },
    addClick() {
      this.isEdit = false
      this.queryShopAsync()
      this.initForm()
      this.addVisible = true
    },
    onSubmit() {
      const vm = this
      vm.$refs.addForm.validate((valid) => {
        if (valid) {
          vm.btnLoading = true
          vm.submitSave()
        }
      })
    },
    // 新增-保存
    submitSave() {
      const params = Object.assign({}, this.addForm)
      delete params.created_at
      delete params.updated_at
      const url = this.tabs === '1' ? 'productPlatformSku' : 'combinationPlatformSku'
      if (this.isEdit) {
        params['product_code'] = params['goods_code']
        this.$http
          .put(`/${url}/${this.addForm.id}`, params)
          .then((res) => {
            if (res.code === 10000) {
              this.$message.success('修改成功')
              if (this.tabs === '1') {
                this.query()
              } else {
                this.handleSearch()
              }
              this.addVisible = false
            }
            this.btnLoading = false
          })
          .catch((err) => {
            this.btnLoading = false
            console.log(err)
          })
      } else {
        this.$http
          .post(`/${url}`, params)
          .then((res) => {
            if (res.code === 10000) {
              this.$message.success('新增成功')
              if (this.tabs === '1') {
                this.query()
              } else {
                this.handleSearch()
              }

              this.addVisible = false
            }
            this.btnLoading = false
          })
          .catch((err) => {
            this.btnLoading = false
            console.log(err)
          })
      }
    },
    // 自定义操作栏
    columnsHandler(cols) {
      const that = this
      return cols.concat({
        width: '200',
        label: '操作',
        align: 'center',
        fixed: 'left',
        propsHandler({
          row
        }) {
          return {
            row,
            delAction: 'productPlatformSku@delete',
            editAction: 'productPlatformSku@update'
          }
        },
        component: operationBtnGroup,
        // listeners 可用于监听自定义组件内部 $emit 出的事件
        listeners: {
          editTableClick(row) {
            that.isEdit = true
            that.addForm = JSON.parse(JSON.stringify(row))
            that.addVisible = true
          },
          deleteTableClick(row) {
            that
              .$confirm('确认要删除？', '提示', {
                distinguishCancelAndClose: true,
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              })
              .then(() => {
                that.$http
                  .delete(`/productPlatformSku/${row.id}`)
                  .then((res) => {
                    if (res.code === 10000) {
                      that.$message.success('删除成功')
                      that.query()
                    }
                  })
                  .catch((err) => {
                    console.log(err)
                  })
              })
              .catch((action) => { })
          }
        }
      })
    },
    createStateFilter(queryString) {
      return (state) => {
        return (
          state.value.toLowerCase().indexOf(queryString.toLowerCase()) !== -1
        )
      }
    },
    handleSelect(data) {
      console.log(data)
      this.addForm.product_id = data.value
      this.addForm.goods_code = data.code
      if (this.tabs === '2') {
        this.addForm.shop_id = data.shop_id
        this.queryShopAsync()
      } else {
        this.addForm.company_id = data.company_id
        this.queryShopAsync(this.addForm.company_id)
      }
    },
    handleSizeChange1(val) {
      this.searchParams.limit = val
      this.query()
    },
    handleCurrentChange1(val) {
      this.searchParams.page = val
      this.query()
    }
  }
}

</script>

<style scoped>
.app-container /deep/.el-select,
.el-autocomplete {
  width: 100%;
}
</style>
